<template>
    <div
        class="text-ellipsis"
        :class="{ show: toggle }"
        ref="refCnt"
        style="line-height: 22px"
    >
        <slot />
        <template v-if="showToggle">
            <div v-if="!toggle" class="zankai" @click="onToggle">...展开</div>
            <span v-else @click="onToggle">收起</span>
        </template>
    </div>
</template>
<script setup>
import { onMounted, toRefs, ref, watch } from "vue";
const props = defineProps({
    line: {
        type: Number,
        default: () => 2,
    },
    text: {
        type: String,
        default: () => "",
    },
});

const { line, text } = toRefs(props);

const refCnt = ref(null);
const toggle = ref(false);
const showToggle = ref(false);

onMounted(() => {
    getHeight();
});

const onToggle = () => {
    toggle.value = !toggle.value;
};

watch(text, () => {
    getHeight();
});

const getHeight = () => {
    const { offsetHeight, style } = refCnt.value;
    const lineHeight = style.lineHeight.replace(/px/g, "") * 1;
    if (offsetHeight > lineHeight) {
        showToggle.value = true;
    }
};
</script>
<style lang="less" scoped>
.text-ellipsis {
    line-height: 22px;
    position: relative;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    word-break: break-all;
    word-wrap: break-word;
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
    -webkit-line-clamp: v-bind(line);
    transition: all 0.25s ease-in-out;
    &.show {
        -webkit-line-clamp: 99999;
    }
    .zankai {
        position: absolute;
        right: 6px;
        bottom: 0;
        background-color: #fff;
        padding-left: 4px;
        color: var(--primary-color);
        cursor: pointer;
    }
    span {
        color: var(--primary-color);
        cursor: pointer;
        margin-left: 2px;
    }
}
</style>
